package com.senseuni.da.ui.dialog;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.senseuni.common.dialog.CBDialogBuilder;
import com.senseuni.common.dialog.OnDialogResultListener;
import com.senseuni.common.utils.IMEUtil;
import com.senseuni.da.R;

public class SimpleEditTextDialog extends CBDialogBuilder {

    private EditText mEditText;

    public SimpleEditTextDialog(Context context) {
        super(context, CBDialogBuilder.DIALOG_STYLE_NORMAL, (float) 0.4);
        initView(context);
    }

    public SimpleEditTextDialog setHint(String hint) {
        if (mEditText != null) {
            mEditText.setHint(hint);
        }
        return this;
    }

    public SimpleEditTextDialog setContent(String content, boolean selectAll) {
        if (mEditText != null) {
            if (!TextUtils.isEmpty(content)) {
                mEditText.setText(content);
                if (selectAll) {
                    mEditText.selectAll();
                }
                mEditText.setSelection(content.length());
            }
        }
        return this;
    }

    private void initView(Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.layout_simple_edit_text, null);
        mEditText = view.findViewById(R.id.et_content);
        setView(view);
        setTouchOutSideCancelable(true);
        showCancelButton(true);
        setButtonClickListener(false, (context1, dialog, whichBtn) -> {
            if (whichBtn == OnDialogBtnClickListener.BUTTON_CONFIRM) {
                String content = getEditContent();
                if (TextUtils.isEmpty(content)) {
                    Toast.makeText(context1.getApplicationContext(), "请输入内容", Toast.LENGTH_SHORT).show();
                    return;
                }
                IMEUtil.hideSoftKeyboard(mEditText);
                if (mListener != null) {
                    mListener.onResult(dialog, content);
                }
            } else if (whichBtn == OnDialogBtnClickListener.BUTTON_CANCEL) {
                dialog.dismiss();
            }
        });
    }

    public String getEditContent() {
        return mEditText.getText().toString().trim();
    }

    private OnDialogResultListener<String> mListener;

    public void setOnResultListener(OnDialogResultListener<String> listener) {
        mListener = listener;
    }


}
